package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.ItemDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;
import csu.web.mypetstore.persistence.impl.ItemDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class RemoveCartAJAXServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        AccountDao accountDao = new AccountDaoImpl();
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        Cart cart = (Cart) session.getAttribute("cart");
        String workingItemId= req.getParameter("workingItemId");

        CartItem cartItem = new CartItem();
        ItemDao itemDao = new ItemDaoImpl();
        Item item = itemDao.getItem(workingItemId);
        cartItem.setItem(item);
        Item item1 = cart.removeItemById(workingItemId);

        if (item1 == null) {
            session.setAttribute("errorMsg", "Attempted to remove null CartItem from Cart.");
        }
        else {
            accountDao.updateShoppingcartTimesByUsernameAndItemid(loginAccount,cartItem);
            session.setAttribute("cart", cart);
        }
    }
}
